from django.shortcuts import render
from rest_framework.generics import ListAPIView,GenericAPIView,CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
# Create your views here.
from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSSerializers, SKUSearchSerializer, SKUHistorySerializer
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet
from goods.utils import PageNum


class CategoriesView(APIView):
    '''
    面包屑导航
    '''

    def get(self,request,pk):
        #1,获取三级分类ｉｄ

        #2,查询三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)

        #3,通过三级分类查询二级分类
        cat2 = cat3.parent

        #4,通过二级分类查询一级分类
        cat1 = cat2.parent

        #5,返回结果
        return Response({
            'cat1':cat1.name,
            'cat2':cat2.name,
            'cat3':cat3.name,
        })



class  SKUSView(ListAPIView):
    '''
    获取当前分类所有商品
    '''
    serializer_class = SKUSSerializers
    # queryset = SKU.objects.filter(category_id=pk)
    pagination_class = PageNum           #分页
    filter_backends = [OrderingFilter]   #过滤排序
    ordering_fields = ('create_time','sales','price')

    # 重写
    def get_queryset(self):
        pk=self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)
    # def get(self, request, pk):



class SKUSearchView(HaystackViewSet):

    index_models = [SKU]
    serializer_class = SKUSearchSerializer

    pagination_class = PageNum



class SKUHistoryView(CreateAPIView,ListAPIView):
    '''
    用户浏览历史记录
    '''

    serializer_class = SKUHistorySerializer

    def get_queryset(self):
        # 1,获取用户
        user = self.request.user
        # 2,建立缓存链接
        conn = get_redis_connection('history')
        # 3,查询缓存数据获取到sku_id
        sku_ids = conn.lrange('history_%s'%user.id,0,100)
        # 4,根据sku_idd查询商品对象
        skus = SKU.objects.filter(id__in=sku_ids)   #[1,2,3]
        return skus

    def get_serializer_class(self):
        # 指定不同请求返回不同序列化器
        if self.request.method=='POST':
            return SKUHistorySerializer
        else:
            return SKUSSerializers




